<template>
  <div class="search">
    <!-- 标题 tittle -->
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)"/>

    <!-- 搜索框 search -->
    <van-search v-model="searchInp" show-action placeholder="请输入搜索关键词">
      <template #action>
        <div @click="goSearch(searchInp)">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史管理 -->
    <div class="search-history" v-if="historyList.length > 0">
      <div class="title">
        <span>最近搜索</span>
        <van-icon name="delete-o" size="16" @click="clear" />
      </div>
      <div class="search-list">
        <van-tag round type="primary" size="large" text-color="#000" plain
        v-for="item in historyList" :key="item" @click="goSearch(item)">
            {{ item }}
        </van-tag>
      </div>
    </div>
  </div>
</template>

<script>
import { getHistoryList, setHistoryList } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchInp: '', // 搜索框的值
      historyList: getHistoryList() // 历史记录
    }
  },
  methods: {
    goSearch (key) {
      // console.log('搜索', key)
      // 1.找 historyList 是否存在 搜索的关键字的下标
      const index = this.historyList.indexOf(key)
      if (index !== -1) {
        // 2.存在相同的的关键字，将原有的关键字移除
        this.historyList.splice(index, 1)
      }
      // 3. 将搜索的关键字 添加到 historyList 最前面 (置顶)
      this.historyList.unshift(key)
      // 4. 将数据存入本地，持久化
      setHistoryList(this.historyList)
      // 5.跳到搜索列表页
      this.$router.push(`/searchLists?search=${key}`)
    },
    clear () {
      this.historyList = []
      setHistoryList(this.historyList)
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-search__action{
  background-color: #c21401;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
}
.title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .search-list{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
</style>
